package com.oazon.moco.lan.util;

import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.multipart.Attribute;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.moco.launcher.bean.MOCO_CONSTANTS;
import com.oazon.sonos.bean.GetMetadata;

import android.util.Log;

public class UrlDecode {

	public static String getUrl(Map<String, String> params, String url,
			String encoding) {
		// 添加url参数
		if (params != null) {
			String[] urls = url.split("[?]");
			if (urls.length > 0) {
				url = urls[0];
			}

			Iterator<String> it = params.keySet().iterator();
			StringBuffer sb = null;
			while (it.hasNext()) {
				String key = it.next();
				String value = params.get(key);
				if (sb == null) {
					sb = new StringBuffer();
					sb.append("?");
				} else {
					sb.append("&");
				}
				sb.append(key);
				sb.append("=");
				sb.append(value);
			}
			url += sb.toString();
		}
		return url;
	}

	public static void parseParameters(Map<String, String> map, String data,
			String encoding) {

		int start = data.indexOf("?") + 1;
		String sub = data.substring(start);
		String[] urlData = sub.split("[&]");

		for (int i = 0; i < urlData.length; i++) {
			String[] parm = urlData[i].split("[=]");
			if (parm.length > 1) {
				map.put(parm[0], parm[1]);
			}
		}
	}

	public static GetMetadata parseUri(String uri) {
		Map<String, String> params = new HashMap<String, String>();
		parseParameters(params, uri, null);
		GetMetadata getMetadata = new GetMetadata();

		String id = params.get("id");
		int index = Integer.parseInt(params.get("index"));
		int count = Integer.parseInt(params.get("count"));
		boolean recursive = Boolean.parseBoolean(params.get("recursive"));
		String provider = params.get("provider");

		if (id == null) {
			getMetadata.setId(MOCO_CONSTANTS.ROOT_ID);
		} else {
			getMetadata.setId(id);
		}

		if (index < 0) {
			getMetadata.setIndex(0);
		} else {
			getMetadata.setIndex(index);
		}
		if (count <= 0) {
			getMetadata.setCount(1);
		} else {
			getMetadata.setCount(count);
		}
		if (provider == null) {
			getMetadata.setProvider(MOCO_CONSTANTS.RECOMMEND_ROOT);
		} else {
			getMetadata.setProvider(provider);
		}
		getMetadata.setRecursive(recursive);
		return getMetadata;
	}

	public static void parseParameters(HttpRequest httpRequest,
			Map<String, String> map) throws IOException {
		HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(httpRequest);
		List<InterfaceHttpData> objects = decoder.getBodyHttpDatas();
		for (InterfaceHttpData interfaceHttpData : objects) {
			map.put(((Attribute) interfaceHttpData).getName(),
					((Attribute) interfaceHttpData).getValue());
		}

		Log.d("test", map.toString());
	}

}
